package com.runfast.paotui.service.impl;

import com.runfast.common.exception.BaseException;
import com.runfast.common.service.BaseService;
import com.runfast.common.web.entity.Result;
import com.runfast.common.web.entity.ResultCode;
import com.runfast.paotui.dao.mapper.OrderMapper;
import com.runfast.paotui.dao.model.*;
import com.runfast.paotui.entity.BicyclingResponse;
import com.runfast.paotui.service.*;
import com.runfast.paotui.task.async.MessagePushTask;
import com.runfast.paotui.utils.AmapUtil;
import com.runfast.paotui.utils.OrderUtil;
import com.runfast.paotui.web.dto.OrderDto;
import com.runfast.waimai.dao.model.WaiMaiRunfastCuseraddress;
import com.runfast.waimai.dao.model.WaiMaiRunfastShopper;
import com.runfast.waimai.service.WaiMaiRunfastCuseraddressService;
import com.runfast.waimai.service.WaiMaiRunfastShopperService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.runfast.paotui.dao.model.Order.FromType.NEARBY;
import static com.runfast.paotui.dao.model.Order.FromType.SPECIFIED;
import static com.runfast.paotui.dao.model.Order.Type.DAIGOU;
import static com.runfast.paotui.dao.model.Order.Type.QUSONGJIAN;

@Slf4j
@Service
@Lazy(false)
public class OrderServiceImpl extends BaseService<Order, Integer, OrderExample> implements OrderService {
    @Autowired
    private WaiMaiRunfastCuseraddressService waiMaiRunfastCuseraddressService;
    @Autowired
    private WaiMaiRunfastShopperService waiMaiRunfastShopperService;
    public List<Order> selectByMapWithPageable(Map<Object,Object> map){
        OrderMapper orderMapper=(OrderMapper)this.mapper;
        return orderMapper.selectByMapWithPageable(map);
    }
    public Integer countByMap(Map<Object,Object> map){
        OrderMapper orderMapper=(OrderMapper)this.mapper;
        return orderMapper.countByMap(map);
    }
    public Integer countJieDanOrPeiSongOrTotalByMap(Map<Object,Object> map){
        OrderMapper orderMapper=(OrderMapper)this.mapper;
        return orderMapper.countJieDanOrPeiSongOrTotalByMap(map);
    }
    public List<Order> selectJieDanAndPeiSongByMap(Map<Object,Object> map){
        OrderMapper orderMapper=(OrderMapper)this.mapper;
        return orderMapper.selectJieDanAndPeiSongByMap(map);
    }

    public List<Order> selectByMapDiaoDu(Map<Object,Object> map){
        OrderMapper orderMapper=(OrderMapper)this.mapper;
        return orderMapper.selectByMapDiaoDu(map);
    }


    public Integer countByMapShouYe(Map<Object,Object> map){
        OrderMapper orderMapper=(OrderMapper)this.mapper;
        return orderMapper.countByMapShouYe(map);
    }

    public Order findFromAndTo(Order order){
        if(order!=null){
            if(order.getDriverId()!=null){
                WaiMaiRunfastShopper shopper=waiMaiRunfastShopperService.selectByPrimaryKey(order.getDriverId());
                if(shopper!=null){
                    order.setShopperName(shopper.getName());
                    order.setShopperMobile(shopper.getMunber());
                }
            }
            if(order.getType()!=null){
                if(order.getType()==DAIGOU){
                    //代购
                    if(order.getFromType()!=null && order.getFromType()==NEARBY){
                         //骑手就近购买
                         if(order.getToId()!=null){
                             WaiMaiRunfastCuseraddress cuseraddress=waiMaiRunfastCuseraddressService.selectByPrimaryKey(order.getToId());
                             if(cuseraddress!=null){
                                 order.setDiaoDuToAddress(cuseraddress.getUseraddress()+cuseraddress.getAddress());
                                 order.setDiaoDuToLat(cuseraddress.getLatitude());
                                 order.setDiaoDuToLng(cuseraddress.getLongitude());
                                 order.setDiaoDuToUserName(cuseraddress.getName());
                                 order.setDiaoDuToMobile(cuseraddress.getMobile());
                             }
                         }
                    }else if(order.getFromType()!=null && order.getFromType()==SPECIFIED){
                        order.setDiaoDuFromAddress(order.getFromAddress());
                        order.setDiaoDuFromLat(order.getFromLat().toString());
                        order.setDiaoDuFromLng(order.getFromLng().toString());
                        if(order.getToId()!=null){
                            WaiMaiRunfastCuseraddress cuseraddress=waiMaiRunfastCuseraddressService.selectByPrimaryKey(order.getToId());
                            if(cuseraddress!=null){
                                order.setDiaoDuToAddress(cuseraddress.getUseraddress()+cuseraddress.getAddress());
                                order.setDiaoDuToLat(cuseraddress.getLatitude());
                                order.setDiaoDuToLng(cuseraddress.getLongitude());
                                order.setDiaoDuToUserName(cuseraddress.getName());
                                order.setDiaoDuToMobile(cuseraddress.getMobile());
                            }
                        }
                    }
                }else if(order.getType()==QUSONGJIAN){
                     //取送件
                    if(order.getToId()!=null){
                        WaiMaiRunfastCuseraddress cuseraddress=waiMaiRunfastCuseraddressService.selectByPrimaryKey(order.getToId());
                        if(cuseraddress!=null){
                            order.setDiaoDuToAddress(cuseraddress.getUseraddress()+cuseraddress.getAddress());
                            order.setDiaoDuToLat(cuseraddress.getLatitude());
                            order.setDiaoDuToLng(cuseraddress.getLongitude());
                            order.setDiaoDuToUserName(cuseraddress.getName());
                            order.setDiaoDuToMobile(cuseraddress.getMobile());
                        }
                    }
                    if(order.getFromId()!=null){
                        WaiMaiRunfastCuseraddress cuseraddress=waiMaiRunfastCuseraddressService.selectByPrimaryKey(order.getFromId());
                        if(cuseraddress!=null){
                            order.setDiaoDuFromAddress(cuseraddress.getUseraddress()+cuseraddress.getAddress());
                            order.setDiaoDuFromLat(cuseraddress.getLatitude());
                            order.setDiaoDuFromLng(cuseraddress.getLongitude());
                        }
                    }
                }
            }
        }
         return order;
    }






    @Autowired
    private RunfastDeliverCostService deliverCostService;

    @Autowired
    private RunfastCuseraddressService cuseraddressService;

    @Autowired
    private RunfastAgentbusinessService agentbusinessService;


    @Autowired
    private RunfastCuserService cuserService;


    @Autowired
    private OrderStatusHistoryService orderStatusHistoryService;


    @Autowired
    private MessagePushTask messagePushTask;

    @Autowired
    private RunfastShopperService shopperService;

   /* @Autowired
    @Lazy
    private PayService payService;*/

    //cz
    public Map<Object, Object> selectByExampleWithPage(Order order, Pageable pageable, Map<String,Date> mapDate, Map<String,List<Integer>> mapList, boolean admin)  {
        OrderExample orderExample = new OrderExample();
        /*if(order.getStatus()!=null){
            orderExample.createCriteria().andStatusEqualTo(order.getStatus());
        }*/

        if(StringUtils.isNotBlank(order.getOrderNo())){
            orderExample.createCriteria().andOrderNoEqualTo(order.getOrderNo());
        }
        /*if(order.getStatus() !=null){
            orderExample.createCriteria().andStatusEqualTo(order.getStatus());
        }*/
        if(null !=mapDate.get("startDate")){
            orderExample.createCriteria().andCreateTimeGreaterThanOrEqualTo(mapDate.get("startDate"));
        }
        if(null !=mapDate.get("endDate")){
            orderExample.createCriteria().andCreateTimeLessThanOrEqualTo(mapDate.get("endDate"));
        }
        if(admin==false){
            if(mapList.get("list") !=null){
                if( mapList.get("list").size()>0){
                    orderExample.createCriteria().andAgentIdIn(mapList.get("list"));
                }
            }
        }else if(admin==true){
            orderExample.createCriteria().andAgentIdIsNotNull();
        }

        List<Order> orderList = mapper.selectByExampleWithPageable(orderExample, pageable);
        long total=mapper.countByExample(orderExample);
        Map<Object,Object> map=new HashMap<Object, Object>();
        map.put("total",total);
        map.put("orderList",orderList);
        return map;
    }


    @Override
    public Result confirm(Order order) {
        Validate.notNull(order);
        Validate.notNull(order.getCuserId(), "order.cuserId 不能为null");
        Order.Type orderType = order.getType();
        Validate.notNull(orderType, "order.type 不能为null");
        if (orderType == DAIGOU) {
            validate(order, Order.Daigou.class);
        }

        if (orderType == QUSONGJIAN) {
            validate(order, Order.Qusongjian.class);
        }

        Validate.notNull(order.getToId(), "order.toId 不能为null");

        RunfastCuseraddress toAddress = cuseraddressService.selectByPrimaryKey(order.getToId());
        if (toAddress == null) return Result.fail(ResultCode.FAIL, "不存在toId对应的收货地址");
        Double toLng = Double.valueOf(toAddress.getLongitude());
        Double toLat = Double.valueOf(toAddress.getLatitude());

        String destination = toLng + "," + toLat;
        RunfastAgentbusiness agentNearBy = null;

        Integer deliveryCost = null;

        if (orderType == DAIGOU) {
            Order.FromType fromType = order.getFromType();
            if (fromType == SPECIFIED) {
                validate(order,  Order.Specified.class);
                Double fromLng = order.getFromLng();
                Double fromLat = order.getFromLat();

                String origin = fromLng + "," + fromLat;


                agentNearBy = agentbusinessService.getAgentNearBy(fromLng, fromLat);
                if (agentNearBy != null) {
                    RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentNearBy.getId());

                    BicyclingResponse bicyclingResponse = AmapUtil.bicycling(origin, destination);
                    if (bicyclingResponse.getErrcode() == 0) {
                        BicyclingResponse.Data data = bicyclingResponse.getData();
                        List<BicyclingResponse.Path> paths = data.getPaths();
                        if (!paths.isEmpty()) {
                            BicyclingResponse.Path path = paths.get(0);
                            Integer distance = path.getDistance();
                            Integer duration = path.getDuration();

                            order.setDistance(distance);
                            order.setDeliveryDuration((int) Math.ceil(duration / 60D));
                            Map<String, Integer> map = deliverCostService.getDeliveryCost(order.getDistance(), null, defaultDeliveryTemplate);
                            deliveryCost = map.get("deliveryFee");
                        }
                    } else {
                        throw new RuntimeException(bicyclingResponse.getErrdetail());
                    }


                } else {
                    return Result.fail(ResultCode.AGENT_NEAR_BY_NOT_EXIST);
                }


            } else if (fromType == NEARBY) {
                validate(order,  Order.NearBy.class);

                agentNearBy = agentbusinessService.getAgentNearBy(order.getUserLng(), order.getUserLat());
                if (agentNearBy != null) {

                    RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentNearBy.getId());
                    Double nocharge = defaultDeliveryTemplate.getNoCharge() == null ? 0d : defaultDeliveryTemplate.getNoCharge();

                    //转换为以米为单位
                    Integer baseDistance = BigDecimal.valueOf(nocharge).multiply(BigDecimal.valueOf(1000)).intValue();
                    order.setDistance(baseDistance);

                    double speed = defaultDeliveryTemplate.getSpeed() == null ? 1d : defaultDeliveryTemplate.getSpeed();
                    int duration = (int) Math.ceil(baseDistance * speed / 100);
                    order.setDeliveryDuration(duration < 15 ? 15 : duration);
                    Map<String, Integer> map = deliverCostService.getDeliveryCost(null, null, defaultDeliveryTemplate);
                    deliveryCost = map.get("deliveryFee");
                } else {
                    return Result.fail(ResultCode.AGENT_NEAR_BY_NOT_EXIST);
                }

            }
        }
        if (orderType == QUSONGJIAN) {
            validate(order,  Order.Qusongjian.class);

            Integer fromId = order.getFromId();

            RunfastCuseraddress fromAddress = cuseraddressService.selectByPrimaryKey(fromId);
            if (fromAddress == null) return Result.fail(ResultCode.FAIL, "不存在fromId对应的取货地址");
            Double fromLng = Double.valueOf(fromAddress.getLongitude());
            Double fromLat = Double.valueOf(fromAddress.getLatitude());
            String origin = fromLng + "," + fromLat;


            agentNearBy = agentbusinessService.getAgentNearBy(fromLng, fromLat);
            if (agentNearBy != null) {
                RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentNearBy.getId());

                BicyclingResponse bicyclingResponse = AmapUtil.bicycling(origin, destination);
                if (bicyclingResponse != null && bicyclingResponse.getErrcode() == 0) {
                    BicyclingResponse.Data data = bicyclingResponse.getData();
                    List<BicyclingResponse.Path> paths = data.getPaths();
                    BicyclingResponse.Path path = paths.get(0);
                    Integer distance = path.getDistance();
                    Integer duration = path.getDuration();

                    order.setDistance(distance);
                    order.setDeliveryDuration((int) Math.ceil(duration / 60d));
                    Map<String, Integer> map = deliverCostService.getDeliveryCost(order.getDistance(), null, defaultDeliveryTemplate);
                    deliveryCost = map.get("deliveryFee");
                } else {
                    throw new RuntimeException(bicyclingResponse.getErrdetail());

                }

            } else {
                return Result.fail(ResultCode.AGENT_NEAR_BY_NOT_EXIST);
            }

        }


        order.setDeliveryCost(deliveryCost);

        Integer amountPayable = 0;
        amountPayable = deliveryCost;
        order.setAmountPayable(amountPayable);


        String orderNo = OrderUtil.generateOrderNo("p");
        order.setOrderNo(orderNo);
        order.setStatus(Order.Status.CREATED);

        order.setCreateTime(new Date());
        order.setUpdateTime(new Date());
        order.setAgentId(agentNearBy.getId());

        this.insertSelective(order);

        OrderStatusHistory orderStatusHistory = new OrderStatusHistory();
        orderStatusHistory.setStatus(Order.Status.CREATED);
        orderStatusHistory.setOrderId(order.getId());
        orderStatusHistory.setCreateTime(new Date());
        orderStatusHistory.setUpdateTime(new Date());
        orderStatusHistoryService.insertSelective(orderStatusHistory);

        messagePushTask.newOrderNotify(orderNo, agentNearBy.getId());

        return Result.ok("下单成功");

    }

    /**
     *
     * //@param driverId
     * //@param orderId
     * @return
     */
   /* @Override
    public Result take(Integer driverId, Integer orderId) {
        Validate.notNull(driverId, "driverId 不能为null");
        Validate.notNull(orderId, "orderId 不能为null");

        Order order = this.selectByPrimaryKey(orderId);
        Validate.notNull(order, "不存在该订单");

        Order.Status status = order.getStatus();
        if (status != Order.Status.PAID) {
            return Result.fail(ResultCode.ILLEGAL_OPERATION, "非法操作，订单当前状态为已支付才能接单");
        }

        Integer agentId = order.getAgentId();

        RunfastAgentbusiness agentbusiness = agentbusinessService.selectByPrimaryKey(agentId);
        BigDecimal agentbusinessCoefficient = agentbusiness.getCoefficient();


        RunfastShopper shopper = shopperService.selectByPrimaryKey(driverId);
        BigDecimal shopperCoefficient = shopper.getCoefficient();


        if (agentbusinessCoefficient != null && shopperCoefficient != null && shopperCoefficient.subtract(agentbusinessCoefficient).doubleValue() >= 0) {

            int plateformIncome = agentbusinessCoefficient.multiply(BigDecimal.valueOf(order.getAmountPaid())).intValue();

            int agentIncome = shopperCoefficient.multiply(BigDecimal.valueOf(order.getAmountPaid())).subtract(BigDecimal.valueOf(plateformIncome)).intValue();

            int driverIncome = order.getAmountPaid() - plateformIncome - agentIncome;

            Order orderUpdate = new Order();
            orderUpdate
                    .withStatus(Order.Status.TAKEN)
                    .withTaken(true)
                    .withTimeTaken(new Date())
                    .withDriverId(driverId)
                    .withDriverIncome(driverIncome)
                    .withAgentIncome(agentIncome)
                    .withPlateformIncome(plateformIncome)
                    .withUpdateTime(new Date());

            OrderExample orderExample = new OrderExample();
            orderExample.createCriteria().andIdEqualTo(orderId)
                    .andStatusEqualTo(Order.Status.PAID.ordinal());
            int count = this.updateByExampleSelective(orderUpdate, orderExample);
            if (count == 1) {

                messagePushTask.takenOrderNotity(order.getOrderNo(), order.getCuserId());

                return Result.ok("接单成功");
            } else {
                return Result.fail(ResultCode.FAIL, "没有可处理的订单");
            }

        } else {
            return Result.fail(ResultCode.PARAMETER_ERROR, "agentbusiness.coefficient和shopper.coefficient不能为null，且shopper.coefficient必须大于等于agentbusiness.coefficient");
        }


    }*/

    /*@Override
    @Async
    public Result cancel(Integer userId, Integer orderId) {

        Validate.notNull(userId, "userId 不能为null");
        Validate.notNull(orderId, "orderId 不能为null");

        OrderExample orderExample = new OrderExample();
        orderExample.createCriteria().andCuserIdEqualTo(userId)
                .andIdEqualTo(orderId);

        List<Order> orders = this.selectByExample(orderExample);
        if (orders.isEmpty()) return Result.fail(ResultCode.FAIL, "该用户下不存在要取消的订单");

        Order order = orders.get(0);
        Order.Status status = order.getStatus();
        if (status == Order.Status.CREATED || status == Order.Status.PAID) {

            Order orderUpdate = new Order();
            orderUpdate
                    .withStatus(Order.Status.CANCELED)
                    .withUpdateTime(new Date());

            OrderExample orderExampleUpdate = new OrderExample();
            orderExampleUpdate.createCriteria().andIdEqualTo(orderId)
                    .andStatusEqualTo(status.ordinal());

            int update = this.updateByExampleSelective(orderUpdate, orderExampleUpdate);

            if (update == 1) {
                if (status == Order.Status.PAID) {

                    Result result = payService.applyRefund(order.getOrderNo(), "", order.getAmountPaid());
                    if (result.isSuccess()) {
                        return Result.ok("取消订单成功，支付金额稍后将原路返还");
                    } else {
                        return Result.fail(ResultCode.FAIL, "取消订单失败,原因：" + result.getErrorMsg());
                    }
                } else {
                    return Result.ok("取消订单成功");
                }

            } else {
                return Result.fail(ResultCode.FAIL, "该用户下不存在要取消的订单");
            }

        } else {
            return Result.fail(ResultCode.FAIL, "骑手已接单，只能取消还未处理的订单");
        }


    }*/

    @Override
    public List<Map<String, Integer>> selectIdUserIdByExample(OrderExample example) {
        return mapper.selectIdUserIdByExample(example);
    }

    @Override
    public Result fillIn(Order order) {
        Validate.notNull(order, "order 不能为null");
        Validate.notNull(order.getType(), "order.type 不能为null");
        Validate.notNull(order.getUserLng(), "order.userLng 不能为null");
        Validate.notNull(order.getUserLat(), "order.userLat 不能为null");


        HashMap<String, Object> data = new HashMap<>();
        Order.Type type = order.getType();
        Integer toId = order.getToId();
        if (toId != null) {
            RunfastCuseraddress toAddress = cuseraddressService.selectByPrimaryKey(toId);

            if (toAddress == null) return Result.fail(ResultCode.FAIL, "不存在toId对应的收货地址");

            Double toLng = Double.valueOf(toAddress.getLongitude());
            Double toLat = Double.valueOf(toAddress.getLatitude());

            String destination = toLng + "," + toLat;

            if (type == DAIGOU) {
                Order.FromType fromType = order.getFromType();
                if (fromType != null) {
                    if (fromType == SPECIFIED) {
                        Double fromLng = order.getFromLng();
                        Double fromLat = order.getFromLat();

                        if (fromLng != null && fromLat != null) {
                            String origin = fromLng + "," + fromLat;
                            RunfastAgentbusiness agentNearBy = agentbusinessService.getAgentNearBy(fromLng, fromLat);

                            if (agentNearBy != null) {
                                RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentNearBy.getId());

                                BicyclingResponse bicyclingResponse = AmapUtil.bicycling(origin, destination);
                                if (bicyclingResponse.getErrcode() == 0) {
                                    BicyclingResponse.Data bycyclingData = bicyclingResponse.getData();
                                    List<BicyclingResponse.Path> paths = bycyclingData.getPaths();
                                    if (!paths.isEmpty()) {
                                        BicyclingResponse.Path path = paths.get(0);
                                        Integer distance = path.getDistance();
                                        Integer duration = path.getDuration();

                                        Integer deliveryDuration = (int) Math.ceil(duration / 60D);

                                        data.put("distance", distance);
                                        data.put("deliveryDuration", deliveryDuration < 15 ? 15 : deliveryDuration);
                                        data.putAll(deliverCostService.getDeliveryCost(distance, null, defaultDeliveryTemplate));

                                        return Result.ok("", data);
                                    } else {
                                        throw new BaseException(ResultCode.SYSTEM_BUSY);
                                    }
                                } else {
                                    throw new RuntimeException(bicyclingResponse.getErrdetail());
                                }


                            } else {
                                return Result.fail(ResultCode.AGENT_NEAR_BY_NOT_EXIST);
                            }
                        }

                    }
                }

            } else {
                Integer fromId = order.getFromId();

                if (fromId != null) {
                    RunfastCuseraddress fromAddress = cuseraddressService.selectByPrimaryKey(fromId);
                    if (fromAddress == null) return Result.fail(ResultCode.FAIL, "不存在fromId对应的取货地址");
                    Double fromLng = Double.valueOf(fromAddress.getLongitude());
                    Double fromLat = Double.valueOf(fromAddress.getLatitude());
                    String origin = fromLng + "," + fromLat;


                    RunfastAgentbusiness agentNearBy = agentbusinessService.getAgentNearBy(fromLng, fromLat);
                    if (agentNearBy != null) {
                        RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentNearBy.getId());

                        BicyclingResponse bicyclingResponse = AmapUtil.bicycling(origin, destination);
                        if (bicyclingResponse != null && bicyclingResponse.getErrcode() == 0) {
                            BicyclingResponse.Data bycyclingData = bicyclingResponse.getData();
                            List<BicyclingResponse.Path> paths = bycyclingData.getPaths();
                            BicyclingResponse.Path path = paths.get(0);
                            Integer distance = path.getDistance();
                            Integer duration = path.getDuration();

                            Integer deliveryDuration = (int) Math.ceil(duration / 60d);

                            data.put("distance", distance);
                            data.put("deliveryDuration", deliveryDuration < 15 ? 15 : deliveryDuration);
                            data.putAll(deliverCostService.getDeliveryCost(distance, order.getGoodsWeight(), defaultDeliveryTemplate));

                            return Result.ok("", data);
                        } else {
                            throw new RuntimeException(bicyclingResponse.getErrdetail());

                        }

                    } else {
                        return Result.fail(ResultCode.AGENT_NEAR_BY_NOT_EXIST);
                    }
                }

            }

        }


        RunfastAgentbusiness agentNearBy = agentbusinessService.getAgentNearBy(order.getUserLng(), order.getUserLat());
        if (agentNearBy != null) {

            RunfastDeliverCost defaultDeliveryTemplate = deliverCostService.getDefaultDeliveryTemplate(agentNearBy.getId());
            Double nocharge = defaultDeliveryTemplate.getNoCharge() == null ? 0d : defaultDeliveryTemplate.getNoCharge();

            //转换为以米为单位
            Integer baseDistance = BigDecimal.valueOf(nocharge).multiply(BigDecimal.valueOf(1000)).intValue();

            double speed = defaultDeliveryTemplate.getSpeed() == null ? 1d : defaultDeliveryTemplate.getSpeed();
            int duration = (int) Math.ceil(baseDistance * speed / 100);
//                            order.setDeliveryDuration(duration < 15 ? 15 : duration);
            Integer deliveryDuration = duration < 15 ? 15 : duration;

            data.put("distance", baseDistance);
            data.put("deliveryDuration", deliveryDuration);
            data.putAll(deliverCostService.getDeliveryCost(null, type == QUSONGJIAN ? order.getGoodsWeight() : null, defaultDeliveryTemplate));

            return Result.ok("", data);

        } else {
            return Result.fail(ResultCode.AGENT_NEAR_BY_NOT_EXIST);
        }

    }

    @Override
    public OrderDto toOrderDto(Order order) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException {
        OrderDto orderDto = new OrderDto();
        Order.Type type = order.getType();

        PropertyUtils.copyProperties(orderDto, order);
        switch (type){
            case DAIGOU:
                Order.FromType fromType = order.getFromType();
                if(fromType==NEARBY){
                    orderDto.setFromAddress("就近购买");
                }
                break;
            case QUSONGJIAN:
                Integer fromId = order.getFromId();

                RunfastCuseraddress runfastCuseraddress = cuseraddressService.selectByPrimaryKey(fromId);
                orderDto.setFromAddress(runfastCuseraddress.getAddress());
                orderDto.setFromName(runfastCuseraddress.getCname());
                orderDto.setFromMobile(runfastCuseraddress.getMobile());
                break;
        }

        Integer toId = order.getToId();

        RunfastCuseraddress runfastCuseraddress = cuseraddressService.selectByPrimaryKey(toId);
        orderDto.setToAddress(runfastCuseraddress.getAddress());
        orderDto.setToName(runfastCuseraddress.getCname());
        orderDto.setToMobile(runfastCuseraddress.getMobile());

        return orderDto;
    }

}